<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\middleware\Auth;
use app\model\BaseOrderStatus;
use app\model\DistrictCodesModel;
use app\model\OrderItemsModel;
use app\model\OrdersModel;
use app\model\ProductSalesSpecsModel;
use app\model\ProductShipping;
use app\model\ProductsModel;
use app\model\RedisModel;
use app\model\ShopsModel;
use app\model\UserAddressesModel;
use app\model\UserFbLogModel;
use app\model\UserSearchHistoryModel;
use app\model\UserShopCarModel;
use app\model\UserUseDiscountCodeLogModel;
use think\App;
use think\Exception;
use think\facade\Db;

class Orders extends Base {

    protected $middleware = [Auth::class];

    private $cacheKey="order:id:";

    private $itemCacheKey="order:item:id:";

    private $orderModel;

    private $orderItemsModel;

    private $productsModel;

    private $shopsModel;

    private $specSalesModel;

    private $productShippingModel;

    private $userAddressesModel;

    private $userSearchHistoryModel;

    private $userUseDiscountCodeLogModel;

    private $userFbLogModel;

    private $req;

    private $page;

    private $limit = 10;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->orderModel = new OrdersModel();

        $this->orderItemsModel = new OrderItemsModel();

        $this->userAddressesModel = new UserAddressesModel();

        $this->productsModel = new ProductsModel();

        $this->shopsModel = new ShopsModel();

        $this->specSalesModel = new ProductSalesSpecsModel();

        $this->productShippingModel = new ProductShipping();

        $this->baseOrderStatusModel = new BaseOrderStatus();

        $this->userSearchHistoryModel = new UserSearchHistoryModel();

        $this->discountCodeModel = new DistrictCodesModel();

        $this->userUseDiscountCodeLogModel = new UserUseDiscountCodeLogModel();

        $this->userFbLogModel = new UserFbLogModel();

        $this->req = request()->param();

        $this->header = request()->header();

        $this->orderModel->batchHandleTimeOutOrder();

        $this->uid = $this->isLogin();
    }




    /*
 * 根据订单状态查询订单列表 by 搜索
 * */
    public function getUserOrderListBySearch(){

        if(!isset($this->req["word"])){
            return $this->fail("请输入关键字");
        }

        if($this->uid && $this->req['word']){
            //添加搜索记录
            $this->userSearchHistoryModel->addOne([
                "uid"=>$this->uid,
                "type"=>2,
                "word"=>$this->req['word']
            ]);
        }


        $where=[];
        $where[] = ['o.uid','=',$this->uid];
        $where[] = ['o.is_delete','=',0];
        $where[] = ['it.product_snapshot|it.spec_snapshot|s.shop_name','LIKE',"%{$this->req["word"]}%"];

        $list = $this->orderModel->getList($where,$this->page,$this->limit,"o.created_at","DESC");

        $total = $this->orderModel->getTotal($where);

        return $this->succData($total,$list);
    }



    /*
  * 根据订单状态查询订单列表
  * */
    public function getUserOrderList(){

        if(!isset($this->req["order_status"])){
            return $this->fail("参数错误:order_status 不能为空");
        }

        $where=[];
        $where[] = ['o.uid','=',$this->uid];
        $where[] = ['o.is_delete','=',0];
        if(isset($this->req["order_status"]) && $this->req["order_status"] != "all" && $this->req["order_status"] != -2){
            $where[] = ['o.aftersale_status','=',0];
            $where[] = ['o.order_status','=',$this->req["order_status"]];
        }elseif ($this->req["order_status"] == -2){
            $where[] = ['o.aftersale_status','<>',0];
        }


        $list = $this->orderModel->getList($where,$this->page,$this->limit,"o.created_at","DESC");

        $total = $this->orderModel->getTotal($where);

        return $this->succData($total,$list);
    }



    /*
     * 创建订单
     * */
    public function getOrderInfo(){

        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        $partnerOrderInfo = [];
        $partnerOrderInfo["order_list"] = [];
        $total_shipping_fee = 0;
        $total_amount = 0;
        $total_pay_amount = 0;
        $total_discount_amount = 0;
        if(substr($this->req["order_id"],0,1) == "L"){
            $where=[];
            $where['p_order_id'] = $this->req["order_id"];
            $where['o.is_delete'] = 0;
            $orderInfo = $this->orderModel->getList($where);
            $partnerOrderInfo["order_list"] = $orderInfo;
            $total_shipping_fee = array_sum(array_column($orderInfo,"total_shipping_fee"));
            $total_amount = array_sum(array_column($orderInfo,"total_amount"));
            $total_pay_amount = array_sum(array_column($orderInfo,"total_pay_amount"));
            $total_discount_amount = array_sum(array_column($orderInfo,"total_discount_amount"));
        }else{
            $orderInfo = $this->orderModel->getInfo($this->req["order_id"]);
            $partnerOrderInfo["order_list"] = [$orderInfo];
            $total_shipping_fee += $orderInfo["total_shipping_fee"];
            $total_amount += $orderInfo["total_amount"];
            $total_pay_amount += $orderInfo["total_pay_amount"];
            $total_discount_amount += $orderInfo["total_discount_amount"];
        }

        $partnerOrderInfo['total_shipping_fee'] =  round($total_shipping_fee / 100,2);
        $partnerOrderInfo['total_amount'] =  round($total_amount / 100,2);
        $partnerOrderInfo['total_pay_amount'] =  round($total_pay_amount / 100,2);
        $partnerOrderInfo['total_discount_amount'] =  round($total_discount_amount / 100,2);

        return  $this->succ($partnerOrderInfo);

    }

    /*
     * 创建订单
     * */
    public function createOrder(){

        $orders = $this->req["orders"];

        if(empty($this->req["address_id"])){
            return $this->fail("请选择收货地址");
        }

        if(!$this->userAddressesModel->isUserAddress($this->uid,$this->req["address_id"])){
            return $this->fail("收货地址不存在");
        }


        $remark = isset($this->req["remark"]) ? $this->req["remark"] : "";

        $receiverInfo =  json_encode($this->userAddressesModel->getInfo($this->req["address_id"]),256);
        //创建订单信息
        $pOrderId = "L".generateOrderId();;
        $partnerOrderList=[];
        $childOrderList=[];
        $shopProductList=[];
        foreach ($orders as $order){

            if(empty($order['spec_id'])){
                return $this->fail("参数错误:spec_id 不能为空");
            }

            if($order['num'] < 1){
                return $this->fail("参数错误:商品数量不合法");
            }

            //检查规格
            $specInfo = $this->specSalesModel->getInfo($order['spec_id']);

            if($specInfo['stock'] - $specInfo['sales_num'] < $order['num']){
                return $this->fail($specInfo["spec_name"]."该规格商品库存不足");
            }
            if($specInfo['spec_status'] != 1){
                return $this->fail($specInfo["spec_name"]."该规格商品已下架");
            }

            //检查商品
            $productBaseInfo =  $this->productsModel->getBaseInfo($specInfo['product_id']);
            if($productBaseInfo['product_status'] != 1){
                return $this->fail($productBaseInfo["product_name"]."该商品已下架");
            }

            //检查商铺
            $shopInfo = $this->shopsModel->getInfo($productBaseInfo['shop_id']);
            if($shopInfo["shop_status"] != 1){
                return $this->fail($shopInfo["shop_name"]."该店铺已下架");
            }

            //如果父级订单不存
            if(!isset($partnerOrderList[$shopInfo["shop_id"]])){
                $partnerOrderList[$shopInfo["shop_id"]]["p_order_id"] = $pOrderId;
                $partnerOrderList[$shopInfo["shop_id"]]["order_id"] = generateOrderId();
                $partnerOrderList[$shopInfo["shop_id"]]["shop_id"] =  $shopInfo["shop_id"];
                $partnerOrderList[$shopInfo["shop_id"]]["uid"] = $this->uid;
                $partnerOrderList[$shopInfo["shop_id"]]["receiver_info"] = $receiverInfo;
                $partnerOrderList[$shopInfo["shop_id"]]["total_amount"] =0;
                $partnerOrderList[$shopInfo["shop_id"]]["total_shipping_fee"]=0;
                $partnerOrderList[$shopInfo["shop_id"]]["total_pay_amount"]=0;
                $partnerOrderList[$shopInfo["shop_id"]]["total_discount_amount"] =0;
                $partnerOrderList[$shopInfo["shop_id"]]["remark"]=$remark;
            }
            //创建子订单
            $childOrder=[];
            $childOrder["order_id"] =   $partnerOrderList[$shopInfo["shop_id"]]["order_id"];
            $childOrder["shop_id"] =  $shopInfo["shop_id"];
            $childOrder["product_id"] =  $specInfo['product_id'];
            $childOrder["spec_id"] =  $order["spec_id"];
            $childOrder["spec_num"] =  $order["num"];
            $childOrder["spec_price"] =  $specInfo['price'];
            $childOrder["spec_pay_price"] =  $specInfo['price'];
            $childOrder["spec_discount_price"] =  $specInfo['price'] - $childOrder["spec_pay_price"];
            $childOrder["spec_total_price"] =  $childOrder["spec_num"]  * $childOrder["spec_price"];
            $childOrder["spec_total_pay_price"] =  $childOrder["spec_num"]  * $childOrder["spec_pay_price"];
            $childOrder["spec_total_discount_price"] =  $childOrder["spec_total_price"]  -  $childOrder["spec_total_pay_price"];
            $childOrder["product_snapshot"] =  json_encode($productBaseInfo,256);
            $childOrder["spec_snapshot"] =  json_encode($specInfo,256);
            $childOrderList[] = $childOrder;
            //存入店铺商品列表
            $shopProductList[$shopInfo["shop_id"]][] = $specInfo['product_id'];
            //计价商品费用
            $partnerOrderList[$shopInfo["shop_id"]]["total_amount"] += $childOrder["spec_total_price"];
            $partnerOrderList[$shopInfo["shop_id"]]["total_pay_amount"] += $childOrder["spec_total_pay_price"];
            $partnerOrderList[$shopInfo["shop_id"]]["total_discount_amount"] += $childOrder["spec_total_discount_price"];
        }

        //获取邮费 根据店铺获取商品列表，从列表中获取最大的费用
        foreach ($shopProductList as $shop_id => $shopProductIds){
            $partnerOrderList[$shop_id]["total_shipping_fee"] = $this->productShippingModel->getProductShippingFee(array_unique($shopProductIds));
            $partnerOrderList[$shop_id]["total_amount"] +=  $partnerOrderList[$shop_id]["total_shipping_fee"];
            $partnerOrderList[$shop_id]["total_pay_amount"] +=  $partnerOrderList[$shop_id]["total_shipping_fee"];
        }

        Db::startTrans();
        $partnerRes = $this->orderModel->bacthAdd($partnerOrderList);
        $childRes = $this->orderItemsModel->batchAdd($childOrderList);
        if($partnerRes && $childRes ){
            Db::commit();
            return $this->succ( $pOrderId,"创建订单成功");
        }else{
            Db::rollback();
            return $this->fail("创建订单失败");
        }
    }



    /**
     * 为订单添加/更新“随缘价”捐赠（支持单订单 or 联合订单）
     * 支持多次修改：每次会先剔除历史随缘价，再重新分摊
     */
    public function addGratuityToOrder()
    {
        $orderId = $this->req["order_id"] ?? '';
        $fbAmountYuan = $this->req['fb_amount'] ?? 0;

        if (empty($orderId)) {
            return $this->fail("参数错误: order_id 不能为空");
        }

        // ======== 🔥 新增：支持 fb_amount = 0，清空随缘价 ========
        if ($fbAmountYuan == 0) {
            return $this->clearGratuity($orderId);
        }

        if ($fbAmountYuan < 1) {
            return $this->fail("随缘价最低为1元");
        }

        $fbAmount = (int)($fbAmountYuan * 100); // 单位：分

        // 判断是否为联合订单（父订单号）
        $isPOrderId = isUnionOrderId($orderId);
        $pOrderId = $isPOrderId ? $orderId : null;

        // 获取所有相关子订单
        if ($isPOrderId) {
            $orderIdList = $this->orderModel->getOrderByPOrderId($pOrderId);
            if (empty($orderIdList)) {
                return $this->fail("订单不存在");
            }
            $orderList = [];
            foreach ($orderIdList as $oid) {
                $orderInfo = $this->orderModel->getInfo($oid);
                if (!$orderInfo || $orderInfo['uid'] != $this->uid) {
                    return $this->fail("订单不存在或无权限");
                }
                $orderList[] = $orderInfo;
            }
            $pOrderId = $orderId; // 使用传入的 p_order_id
        } else {
            if (!$this->orderModel->isUserOrder($this->uid, $orderId)) {
                return $this->fail("订单不存在或无权限");
            }

            $orderInfo = $this->orderModel->getInfo($orderId);
            if (!$orderInfo) {
                return $this->fail("订单数据异常");
            }
            $orderList = [$orderInfo];
            $pOrderId = $orderInfo['p_order_id'];
        }

        // 检查订单状态：必须是待支付（status = 0）
        foreach ($orderList as $order) {
            if ($order['order_status'] != 0) {
                return $this->fail("订单状态不合法，仅支持待支付订单添加随缘价");
            }
        }

        // === 关键修改：还原原始金额（剔除历史随缘价） ===
        $totalOriginalAmount = 0;
        $orderOriginalMap = []; // 保存还原后的原始金额，用于后续分摊
        $itemOriginalMap = [];  // 保存每个商品项的原始支付价（不含 fb）

        foreach ($orderList as $pOrder) {
            $orderId = $pOrder['order_id'];
            $fbDeduct = (int)$pOrder['total_fb_amount']; // 历史随缘价金额（分）

            // 还原主订单金额：减去历史随缘价
            $originalTotalAmount = $pOrder['total_amount'] - $fbDeduct;
            $totalOriginalAmount += $originalTotalAmount;

            $orderOriginalMap[$orderId] = [
                'order_id' => $pOrder['order_id'],
                'original_total_amount' => $originalTotalAmount,
                'old_fb_amount' => $fbDeduct,
            ];

            // 查询商品项并还原 spec_total_pay_price
            $childItems = $this->orderItemsModel->getOrderItemsList($orderId);
            $originalItems = [];

            foreach ($childItems as $item) {
                $oldFbPrice = (int)$item['spec_fb_price'];
                $originalPayPrice = $item['spec_total_pay_price'] - $oldFbPrice; // 还原原始支付价
                $originalItems[] = [
                    'order_item_id' => $item['order_item_id'],
                    'spec_id' => $item['spec_id'],
                    'original_pay_price' => $originalPayPrice,
                    'old_fb_price' => $oldFbPrice,
                ];
            }

            $itemOriginalMap[$orderId] = $originalItems;
        }

        if ($totalOriginalAmount <= 0) {
            return $this->fail("订单原始金额异常，无法添加随缘价");
        }

        // === 开始分摊新随缘价 ===
        $updatedParentOrders = [];
        $updatedChildOrders = [];
        $fbLog = [];
        $itemIdList = [];

        $rate = $fbAmount / $totalOriginalAmount; // 新的分摊率
        $remainingFb = $fbAmount;

        $orderKeys = array_keys($orderList);
        $lastIndex = count($orderKeys) - 1;

        foreach ($orderList as $index => $pOrder) {
            $orderId = $pOrder['order_id'];
            $isLast = ($index === $lastIndex);

            $originalData = $orderOriginalMap[$orderId];
            $allocated = $isLast ? $remainingFb : (int)($originalData['original_total_amount'] * $rate);
            $allocated = min($allocated, $remainingFb);

            // 更新主订单：新总金额 = 原始金额 + 新随缘价
            $newTotalAmount = $originalData['original_total_amount'] + $allocated;
            $newTotalPayAmount = $newTotalAmount; // 假设 total_pay_amount == total_amount

            $updatedParentOrders[] = [
                'order_id' => $orderId,
                'total_amount' => $newTotalAmount,
                'total_pay_amount' => $newTotalPayAmount,
                'total_fb_amount' => $allocated,
            ];

            // 记录福贝日志（可考虑记录是“新增”还是“更新”）
            $fbLog[] = [
                'uid' => $this->uid,
                'fb' => $allocated,
                'type' => 'order',
                'p_order_id' => $pOrderId,
                'order_id' => $orderId,
                'title' => '购物奖励',
                'description' => '随缘价奖励',
                'created_at' => date('Y-m-d H:i:s'),
            ];

            // 分摊到商品项
            $childItems = $itemOriginalMap[$orderId];
            $childPayTotal = array_sum(array_column($childItems, 'original_pay_price'));
            $fbRemainingForChild = $allocated;

            if ($childPayTotal <= 0) {
                // 特殊：原始支付金额为0，全部给最后一个
                foreach ($childItems as $idx => $item) {
                    $isLastItem = ($idx === count($childItems) - 1);
                    $childAllocated = $isLastItem ? $fbRemainingForChild : 0;

                    $updatedChildOrders[] = [
                        'order_item_id' => $item['order_item_id'],
                        'spec_fb_price' => $childAllocated,
                    ];
                    $itemIdList[] = $item['order_item_id'];
                }
            } else {
                $itemRate = $allocated / $childPayTotal;
                $lastItemIndex = count($childItems) - 1;

                foreach ($childItems as $idx => $item) {
                    $isLastItem = ($idx === $lastItemIndex);
                    $childAllocated = $isLastItem
                        ? $fbRemainingForChild
                        : (int)($item['original_pay_price'] * $itemRate);

                    $childAllocated = min($childAllocated, $fbRemainingForChild);

                    $updatedChildOrders[] = [
                        'order_item_id' => $item['order_item_id'],
                        'spec_fb_price' => $childAllocated,
                    ];

                    $fbRemainingForChild -= $childAllocated;
                    $itemIdList[] = $item['order_item_id'];
                }
            }

            $remainingFb -= $allocated;
        }

        // === 事务更新 ===
        Db::startTrans();
        try {
            $updateParentRes = !empty($updatedParentOrders) ? $this->orderModel->batchUpdate($updatedParentOrders) : true;
            $updateChildRes = !empty($updatedChildOrders) ? $this->orderItemsModel->batchUpdate($updatedChildOrders) : true;
            $logRes = !empty($fbLog) ? $this->userFbLogModel->batchAdd($fbLog) : true;

            if ($updateParentRes && $updateChildRes && $logRes) {
                $this->delCache($orderId);
                $this->delItemCache($itemIdList);
                Db::commit();
                return $this->succ([
                    'p_order_id' => $pOrderId,
                    'total_fb_amount' => $fbAmountYuan,
                ], "成功更新随缘价奖励");
            } else {
                throw new \Exception("数据库更新失败");
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->fail("添加随缘价失败：" . $e->getMessage());
        }
    }


    /**
     * 清空指定订单的随缘价（金额还原 + 删除捐赠记录）
     * @param string $orderId
     * @return array
     */
    private function clearGratuity($orderId)
    {
        $isPOrderId = isUnionOrderId($orderId);
        $orderList = [];
        $pOrderId = null;
        if ($isPOrderId) {
            $subOrderIds = $this->orderModel->getOrderByPOrderId($orderId);
            if (empty($subOrderIds)) {
                return $this->fail("联合订单不存在");
            }
            foreach ($subOrderIds as $oid) {
                $orderInfo = $this->orderModel->getInfo($oid);
                if (!$orderInfo || $orderInfo['uid'] != $this->uid) {
                    return $this->fail("订单不存在或无权限");
                }
                if ($orderInfo['order_status'] != 0) {
                    return $this->fail("订单状态不合法，仅支持待支付订单操作");
                }
                $orderList[] = $orderInfo;
            }
            $pOrderId = $orderId;
        } else {
            if (!$this->orderModel->isUserOrder($this->uid, $orderId)) {
                return $this->fail("订单不存在或无权限");
            }
            $orderInfo = $this->orderModel->getInfo($orderId);
            if (!$orderInfo || $orderInfo['order_status'] != 0) {
                return $this->fail("订单状态不合法或数据异常");
            }
            $orderList = [$orderInfo];
            $pOrderId = $orderInfo['p_order_id'] ?: $orderId;
        }

        // === 还原原始金额（剔除历史随缘价）===
        $updatedParentOrders = [];
        $updatedChildOrders = [];
        $fbLogOrderIds = []; // 用于删除捐赠记录
        $allOrderIds = [];

        foreach ($orderList as $order) {
            $orderId = $order['order_id'];
            $oldFbAmount = (int)$order['total_fb_amount'];

            // 还原主订单金额
            $originalTotal = $order['total_amount'] - $oldFbAmount;
            $updatedParentOrders[] = [
                'order_id' => $orderId,
                'total_amount' => $originalTotal,
                'total_pay_amount' => $originalTotal,
                'total_fb_amount' => 0,
            ];

            // 清空商品项随缘价
            $items = $this->orderItemsModel->getOrderItemsList($orderId);
            foreach ($items as $item) {
                $updatedChildOrders[] = [
                    'order_item_id' => $item['order_item_id'],
                    'spec_fb_price' => 0,
                ];
            }

            $fbLogOrderIds[] = $orderId;
            $allOrderIds[] = $orderId;
        }

        // === 事务处理 ===
        Db::startTrans();
        try {
            $updateParent = $this->orderModel->batchUpdate($updatedParentOrders);
            $updateChild = $this->orderItemsModel->batchUpdate($updatedChildOrders);

            // 🔥 删除历史捐赠记录（关键）
            $deleteLog = true;
            if (!empty($fbLogOrderIds)) {
                // 假设日志表可通过 order_id 删除
                $deleteLog = $this->userFbLogModel->deleteByOrderIds($fbLogOrderIds);
            }
            if ($updateParent && $updateChild && $deleteLog) {
                foreach ($allOrderIds as $oid){
                    $this->delCache($oid);
                }
                $this->delItemCache(array_column($updatedChildOrders, 'order_item_id'));
                Db::commit();
                return $this->succ([
                    'p_order_id' => $pOrderId,
                    'total_fb_amount' => 0.00,
                ], "已清空随缘价并删除捐赠记录");
            } else {
                throw new \Exception("数据库更新失败");
            }
        } catch (\Exception $e) {
            Db::rollback();
                        $exceptionlog = '文件 [' . $e->getFile() . '] 第 ' . $e->getLine() . ' 行出现未处理的异常' . PHP_EOL;
//            $exceptionlog .= '代码:' . $e->getCode() . PHP_EOL;
//            $exceptionlog .= '信息:' . $e->getMessage() . PHP_EOL;
//            $exceptionlog .= '跟踪信息：' . $e->getTraceAsString();
//            echo $exceptionlog;die;
            return $this->fail("清空随缘价失败：" . $e->getMessage());
        }
    }



    /*
     * 使用优惠劵
     * */
    public function useDiscountCode(){

        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }


        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        if(isUnionOrderId($this->req["order_id"])){
            $orderIdList = $this->orderModel->getOrderByPOrderId($this->req["order_id"]);
        }else{
            $orderIdList[] =   $this->req["order_id"];
        }


        foreach ($orderIdList as $orderId){
            if($this->orderModel->getOrderStatus($orderId) != 0){
                return $this->fail("订单状态不合法");
            }
        }

        if(!isset($this->req["district_code"]) || empty($this->req["district_code"])){
            return $this->fail("优惠码格式不正确");
        }

        $districtCode = trim($this->req["district_code"]);
        if(strlen($districtCode) != 8){
            return $this->fail("优惠码不存在");
        }

        try {
            $districtCodeInfo = $this->discountCodeModel->useDistrictCode($this->uid,$districtCode);
        }catch (Exception $e){
            return $this->fail($e->getMessage());
        }

        $category_ids = explode(",",$districtCodeInfo["category_ids"]);

        Db::startTrans();
        $where=[];
        $where[] = ["order_id","IN",$orderIdList];
        $orderItemList = $this->orderItemsModel->getList($where);
        $partnerOrderList = [];
        $itemIdList =[];
        foreach ($orderItemList as $specInfo){
            $itemIdList[] = $specInfo["order_item_id"];
            if(!in_array($specInfo["product_snapshot"]["category_id"],$category_ids)){
                return $this->fail( "优惠劵仅限 ".$districtCodeInfo["use_desc"]." 使用");
            }
            $childOrder = [];
            $childOrder["spec_pay_price"] =  (int)($specInfo['spec_price'] * $districtCodeInfo["discount_val"]);
            $childOrder["district_code"] =  $districtCode;
            $childOrder["spec_discount_price"] =  $specInfo['spec_price'] - $childOrder["spec_pay_price"];
            $childOrder["spec_total_pay_price"] =  $specInfo["spec_num"]  * $childOrder["spec_pay_price"];
            $childOrder["spec_total_discount_price"] =  $specInfo["spec_total_price"]  -  $childOrder["spec_total_pay_price"];
            if(!isset($partnerOrderList[$specInfo["order_id"]])){
                $partnerOrderList[$specInfo["order_id"]] =[];
                $partnerOrderList[$specInfo["order_id"]]["total_discount_amount"] = 0;
            }
            $partnerOrderList[$specInfo["order_id"]]["total_discount_amount"] += $childOrder["spec_total_discount_price"];
            try {
                $itemRes =  $this->orderItemsModel->where("order_item_id",$specInfo["order_item_id"])->save($childOrder);
            }catch (Exception $e){
                Db::rollback();
                return $this->fail("使用优惠码异常：".$e->getMessage());
            }

            if(!$itemRes){
                Db::rollback();
                return $this->fail("使用优惠码失败");
            }
        }

        foreach ($partnerOrderList as $order_id => $pOrderInfo){
            try {
            $pOrderRes = $this->orderModel->where("order_id",$order_id)->save([
                "total_pay_amount" => $this->orderModel->getOrderTotalAmount($order_id) - $pOrderInfo["total_discount_amount"],
                "total_discount_amount" => $pOrderInfo["total_discount_amount"],
                "district_code" => $districtCode,
            ]);
            }catch (Exception $e){
                Db::rollback();
                return $this->fail("使用优惠码异常：".$e->getMessage());
            }

            if(!$pOrderRes){
                Db::rollback();
                return $this->fail("使用优惠码失败");
            }
        }

        try {
            $districtCodeRes = $this->userUseDiscountCodeLogModel->insertGetId([
                "code"=>$districtCode,
                "uid"=>$this->uid,
                "order_id"=>$this->req["order_id"],
            ]);
        }catch (Exception $e){
            Db::rollback();
            return $this->fail("使用优惠码异常：".$e->getMessage());
        }

        if(!$districtCodeRes){
            Db::rollback();
            return $this->fail("使用优惠码失败");
        }

        //清理订单缓存
        $this->delCache($this->req["order_id"]);
        $this->delItemCache($itemIdList);

        Db::commit();

        return $this->succ( $this->req["order_id"],"使用优惠码成功");

    }






    /*
     * 清理已关闭的订单
     *
     * */
    public function cancelOrder(){
        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        $where=[];
        $where['uid'] = $this->uid;
        $where['order_id|p_order_id'] = $this->req["order_id"];
        $where['is_delete'] = 0;

        $res = $this->orderModel->updateAll($where,[
            "order_status"=>-1,
            "cancel_time"=>date("Y-m-d H:i:s",time())
        ]);

        $where=[];
        $where['uid'] = $this->uid;
        $where['order_id'] = $this->req["order_id"];
        if($this->userUseDiscountCodeLogModel->getTotal($where) > 0){
            $useDiscountRes = $this->userUseDiscountCodeLogModel->where($where)->delete();
        }else{
            $useDiscountRes = true;
        }

        Db::startTrans();

        if($res && $useDiscountRes){

            $this->delCache($this->req["order_id"]);

            Db::commit();

            return $this->succ("操作成功");

        }else{

            Db::rollback();

            return $this->fail("操作成功");

        }
    }


    /*
     * 确认收获
     * */
    public function confirmOrder(){
        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        $order_status = $this->orderModel->getOrderStatus($this->req["order_id"]);
        if(!in_array($order_status,[2,3])){
            return $this->fail("订单状态错误");
        }
        $where=[];
        $where['uid'] = $this->uid;
        $where['order_id'] = $this->req["order_id"];

        $res = $this->orderModel->updateAll($where,[
            "order_status"=>4,
            "confirm_time"=>date("Y-m-d H:i:s",time())
        ]);

        if($res){

            $this->delCache($this->req["order_id"]);

            return $this->succ("操作成功");

        }else{

            return $this->fail();

        }
    }


    /*
   * 清理已关闭的订单
   *
   * */
    public function deleteOrder(){

        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        $where=[];
        $where['uid'] = $this->uid;
        $where['order_id|p_order_id'] = $this->req["order_id"];
        $where['is_delete'] = 0;

        $res = $this->orderModel->updateAll($where,[
            "is_delete"=>1,
            "delete_time"=>date("Y-m-d H:i:s",time())
        ]);

        if($res){

            $this->delCache($this->req["order_id"]);

            return $this->succ("操作成功");

        }else{

            return $this->fail();

        }
    }



    /*
     * 修改订单地址
     *
     * */
    public function editOrderAddress(){

        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }


        if(empty($this->req["address_id"])){
            return $this->fail("参数错误:address_id 不能为空");
        }


        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        if(!$this->userAddressesModel->isUserAddress($this->uid,$this->req["address_id"])){
            return $this->fail("请选择地址");
        }

        $ids = $this->orderModel->getOrderByPOrderId($this->req["order_id"]);
        foreach ($ids as $id){
            $orderStatus = $this->orderModel->getOrderStatus($id);
            if(!in_array($orderStatus,[0,1])){
                return $this->fail("存在发货状态订单，不允许修改地址");
            }
        }

        $newAddressInfo = $this->userAddressesModel->getInfo($this->req["address_id"]);
        if($this->orderModel->isOrderHaveEditAddress($this->req["order_id"])){
            return  $this->fail("存在修改记录，仅可修改地址一次");
        }

        //修改地址
        $res = $this->orderModel->editOrderAddress($this->req["order_id"],$newAddressInfo);

        if($res){

            $this->delCache($this->req["order_id"]);

            return $this->succ("操作成功");

        }else{

            return $this->fail();

        }
    }



    /*
     * 修改订单备注
     *
     * */
    public function editOrderRemark(){

        if(empty($this->req["order_id"])){
            return $this->fail("参数错误:order_id 不能为空");
        }


        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        if(isUnionOrderId($this->req["order_id"])){
            $ids = $this->orderModel->getOrderByPOrderId($this->req["order_id"]);
            foreach ($ids as $id){
                $orderStatus = $this->orderModel->getOrderStatus($id);
                if(!in_array($orderStatus,[0,1])){
                    return $this->fail("存在已发货状态订单，不允许修改备注");
                }
            }
        }else{
            $orderStatus = $this->orderModel->getOrderStatus($this->req["order_id"]);
            if(!in_array($orderStatus,[0,1])){
                return $this->fail("订单状态不允许修改备注");
            }
        }

        //修改备注
        $res = $this->orderModel->editOrderRemark($this->req["order_id"], $this->req["remark"]);

        if($res){

            $this->delCache($this->req["order_id"]);

            return $this->succ("操作成功");

        }else{

            return $this->fail();

        }
    }


    public function delCache($id)
    {
        $redisModel = new RedisModel();

        $ids = $this->orderModel->getOrderByPOrderId($id);


        foreach ($ids as $id){
            $redisModel->delete($this->cacheKey.$id);
        }

        return true;
    }


    public function delItemCache($itemIdList)
    {
        $redisModel = new RedisModel();

        foreach ($itemIdList as $id){
            $redisModel->delete($this->itemCacheKey.$id);
        }

        return true;
    }

}
